package router

import (
	"fileServer/ginerr"
	"fileServer/global"
	"fileServer/handle"
	"fileServer/setting"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
	"strconv"
)

func Run() {
	logfile, err := os.Create("./gin_http.log")
	if err != nil {
		fmt.Println("Could not create log file")
	}
	gin.SetMode(gin.DebugMode)
	// 定义多个写入器
	writers := []io.Writer{
		logfile,
		os.Stdout}
	gin.DefaultWriter = io.MultiWriter(writers...)

	r := gin.Default()
	r.LoadHTMLGlob("templates/*")
	r.NoRoute(ginerr.HandleNotFound)
	// 注意Recover 尽量第一个被加载, 不然前面加载的中间件或者路由将不能被拦截
	r.Use(ginerr.Recover)

	relativePath := setting.Setting.PrefixURL + "/*" + setting.Setting.URLKey
	r.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, setting.Setting.PrefixURL)
		return
	})
	r.GET("/status", func(c *gin.Context) {
		global.GetResult(c).Success("ok")
	})
	r.GET(relativePath, handle.FileListInfo)
	r.POST(setting.Setting.UploadPath, handle.UploadFile)
	r.POST(setting.Setting.DeletePath, handle.DeleteFile)
	r.POST(setting.Setting.MkdirPath, handle.MakeDir)
	r.POST(setting.Setting.MD5Path, handle.GetMD5)
	//r.StaticFS("/", http.Dir("."))
	addr := setting.Setting.Host + ":" + strconv.Itoa(setting.Setting.Port)
	r.Run(addr) // listen and serve on 0.0.0.0:8080

}
